package com.shushan.home;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.accessibility.PermissionAccessOpenActivity;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBeanDao;
import com.shushan.home.bean.UpdateBean;
import com.shushan.invitecode.InviteCalendarActivity;
import com.shushan.lockscreen.EyeSleepFloatWindow;
import com.shushan.lockscreen.EyeSleepWindowManager;
import com.shushan.login.LoginOrRegisterActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.pages.ExerciseRecordActivity;
import com.shushan.pages.InviteForFreeUseActivity;
import com.shushan.pages.MyCollectionActivity;
import com.shushan.pages.MyStarActivity;
import com.shushan.pages.MyWrongTopicActivity;
import com.shushan.pages.OpenVipSpendActivity;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.service.DaemonService;
import com.shushan.service.DialRTAService;
import com.shushan.service.PlayerMusicService;
import com.shushan.setting.ParentSettingActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.VerificationCodeView;
import com.shushan.util.DateUtils;
import com.shushan.util.DeviceUtil;
import com.shushan.util.DialogUtil;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.versionupdate.entity.VersionUpdateConfig;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


/**
 * @ClassName: HomeActivity
 * @Desciption: 首页
 * @author: yichaohua
 * @date: 2018-07-16
 */
public class HomeActivity extends BaseActivity implements View.OnClickListener, VerificationCodeView.OnCodeFinishListener, OnControlListener {

    private static final String TAG = "HomeActivity";


    private ParentFragmet parentFragmet;
    private ChildMainFragment childFragment;
    private LinearLayout changeLayout;
    private TextView changeTextView;
    private ImageView backImageView;
    //抽屉上的元素
    private DrawerLayout mDrawerLayout;
    private TextView currentChildText;
    private TextView tvLevelTerm;
    private RelativeLayout rlStarNum;
    private TextView tvStarNum;
    private RelativeLayout myCollection;
    private RelativeLayout myWrongTopic;
    private RelativeLayout mExerciseRecord;
    private RelativeLayout parentSet;
    private RelativeLayout myStar;
    private TextView mlogout;

    private TextView titleHintText;
    private TextView titleModeText;

    private Dialog changeToParentDialog;
    private Dialog noVipDialog;
    private Dialog vipTimeEndDialog;
    private VerificationCodeView veriCodeView;

    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int clickType = 0;//点击类型 1:家长设置 2:学生模式切换到家长模式 3:退出登录
    private String versonName;
    private int firstTime = 0;

    private Handler mHandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    getLoopUserinfo();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.home_activity);

        firstTime = getIntent().getIntExtra("firstTime",0);

        ScreenManager sm = new ScreenManager();
        if(!sm.setDeepStatusBar(true,this)){
            findViewById(R.id.titlebar_divider).setVisibility(View.GONE);
        }

        initView();

        initFragment();

        mHandler.sendEmptyMessageDelayed(0,500);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        firstTime = intent.getIntExtra("firstTime",0);
    }

    @Override
    protected void onResume() {
        super.onResume();

        ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
        if(currentChildBean != null){
            currentChildText.setText(currentChildBean.childName);
            tvStarNum.setText(currentChildBean.stars + "");
            tvLevelTerm.setText(ToolUtils.getChildGradeStr(currentChildBean));
        }

        boolean isNotFirstHome = SharedPreferencesUtils.getBooleanDate(Constants.APP_NOT_FIRST_HOME_SHAREPREFERS_KEY);
        if(isNotFirstHome && firstTime == 1){
            firstTime = 0;
            DialogUtil.showFirstTimeLoginDialog(this);
        }else {
            getUpdate();
        }

        SharedPreferencesUtils.setBooleanDate(Constants.APP_NOT_FIRST_HOME_SHAREPREFERS_KEY,true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(changeToParentDialog != null){
            changeToParentDialog.dismiss();
        }

        if(noVipDialog != null){
            noVipDialog.dismiss();
        }

        if(vipTimeEndDialog != null){
            vipTimeEndDialog.dismiss();
        }
    }

    private void initView() {
        titleModeText = findViewById(R.id.actionbar_left_mode_tv);
        titleHintText = findViewById(R.id.actionbar_left_hint_tv);
        backImageView = findViewById(R.id.actionbar_left_back_img);
        backImageView.setOnClickListener(this);
        mDrawerLayout = findViewById(R.id.drawer_layout_main);
        //允许抽屉滑出
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        changeLayout = findViewById(R.id.actionbar_right_change_layout);
        changeLayout.setOnClickListener(this);
        changeTextView = findViewById(R.id.actionbar_right_change_tv);
        currentChildText = findViewById(R.id.tv_user_name);
        tvLevelTerm = findViewById(R.id.tv_level_term);
        rlStarNum = findViewById(R.id.rl_star_num);
        rlStarNum.setOnClickListener(this);
        tvStarNum = findViewById(R.id.tv_star_num);
        myCollection = findViewById(R.id.rl_list_my_collection);
        myCollection.setOnClickListener(this);
        myWrongTopic = findViewById(R.id.rl_list_my_wrong_topic);
        myWrongTopic.setOnClickListener(this);
        mExerciseRecord = findViewById(R.id.rl_list_exercise_record);
        mExerciseRecord.setOnClickListener(this);
        parentSet = findViewById(R.id.rl_list_parent_set);
        parentSet.setOnClickListener(this);
        myStar = findViewById(R.id.rl_list_my_star);
        myStar.setOnClickListener(this);
        mlogout = findViewById(R.id.tv_logout);
        mlogout.setOnClickListener(this);
    }

    private void initFragment() {
        childFragment = new ChildMainFragment();
        parentFragmet = new ParentFragmet();

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Bundle bundle = new Bundle();
        bundle.putString("","");
        childFragment.setArguments(bundle);
        ft.replace(R.id.home_fragment,childFragment).commit();

        changeTextView.setText("家长模式");
        titleModeText.setText("学习");
        titleHintText.setVisibility(View.VISIBLE);

        boolean isNotFirstHome = SharedPreferencesUtils.getBooleanDate(Constants.APP_NOT_FIRST_HOME_SHAREPREFERS_KEY);
        if(!isNotFirstHome){
            startActivity(ControlGuideActivity.class);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.actionbar_right_change_layout:
                changeMode();
                break;
            case R.id.actionbar_left_back_img:
                openDrawer();
                break;
            case R.id.rl_star_num:
                if(isVipValide()){
                    closeDrawer();
                    startActivity(MyStarActivity.class);
                    UmengEventUtil.onEvent(shuShanApplication,"my_star_click_id");
                }
                break;
            case R.id.rl_list_my_collection:
                if(isVipValide()){
                    closeDrawer();
                    startActivity(MyCollectionActivity.class);
                    UmengEventUtil.onEvent(shuShanApplication,"my_collection_click_id");
                }
                break;
            case R.id.rl_list_my_wrong_topic:
                if(isVipValide()){
                    closeDrawer();
                    startActivity(MyWrongTopicActivity.class);
                    UmengEventUtil.onEvent(shuShanApplication,"my_wrong_click_id");
                }
                break;
            case R.id.rl_list_exercise_record:
                if(isVipValide()){
                    closeDrawer();
                    startActivity(ExerciseRecordActivity.class);
                    UmengEventUtil.onEvent(shuShanApplication,"exercise_record_click_id");
                }
                break;
            case R.id.rl_list_parent_set://家长设置
                if(isVipValide()){
                    if(changeTextView.getText().equals("家长模式")){
                        clickType = 1;
//                        veriCodeView = DialogUtil.showInputParentPswDialog(this, this, this);
                    }else {
                        startActivity(ParentSettingActivity.class);
                    }

                    closeDrawer();
                }
                break;
            case R.id.rl_list_my_star://我的学贝
                if(isVipValide()){
                    startActivity(MyStarActivity.class);
                    closeDrawer();
                    UmengEventUtil.onEvent(shuShanApplication,"my_star_click_id");
                }
                break;
            case R.id.tv_logout:
                logout();
                break;
            case R.id.btn_find_back_psw://家长设置dialog：找回密码
                DialogUtil.showForgetPswDialog(this,this);
                break;
            case R.id.btn_cancel://家长设置dialog：取消
                DialogUtil.dismissParentSetDialog();
                break;
            case R.id.iv_close_no_bg://忘记密码dialog：×
                DialogUtil.dismissDialog();
                break;
            case R.id.iv_client_phone_num://忘记密码dialog：客服电话
                DialCustom();
                break;
            case R.id.rl_btn_buy_vip:
                startActivity(OpenVipSpendActivity.class);
                if(vipTimeEndDialog != null){
                    vipTimeEndDialog.dismiss();
                }
                break;
            case R.id.rl_btn_invite:
                startActivity(InviteForFreeUseActivity.class);
                if(vipTimeEndDialog != null){
                    vipTimeEndDialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    private void DialCustom() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(isChildControl && !SystemUtils.checkUsagePermission(this)){
            showNoUsageDialog();
            return;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + Constants.CLIENT_PHONE_NUM));
            startActivityAllow(intent);
            DialogUtil.dismissDialog();
            DialogUtil.dismissParentSetDialog();
        }catch (SecurityException se){
            se.printStackTrace();
            showToast("没有打电话权限");
            return;
        }

        if(isChildControl){
            ActivityStackManager.getActivityStackManager().popAllActivity();
            Intent intent = new Intent(this,DialRTAService.class);
            intent.putExtra("allowPackName",Constants.ALLOW_DIAL_PACK_NAME);
            startService(intent);
        }
    }

    private void changeMode() {
        if(changeTextView.getText().equals("家长模式")){
            clickType = 2;
            showToParentDialog();
            UmengEventUtil.onEvent(shuShanApplication,"parent_mode_change_id");
        }else {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.home_fragment,childFragment).commit();
            changeTextView.setText("家长模式");
            titleModeText.setText("学习");
            titleHintText.setVisibility(View.VISIBLE);
        }
    }

    private void showToParentDialog() {
        changeToParentDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        changeToParentDialog.setContentView(R.layout.change_to_parent_dialog);
        changeToParentDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

        veriCodeView = changeToParentDialog.findViewById(R.id.verification_code_view);
        veriCodeView.setOnCodeFinishListener(this);
        Button coloseButton = changeToParentDialog.findViewById(R.id.btn_cancel);
        coloseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeToParentDialog.dismiss();
            }
        });

        changeToParentDialog.setCancelable(false);

        if(!changeToParentDialog.isShowing()){
            changeToParentDialog.show();
        }
    }

    @Override
    public void onComplete(String content) {
        if(StringTools.pswValide(content)){
            Log.i(TAG,"clickType=" + clickType);
            if(clickType == 1){
                startActivity(ParentSettingActivity.class);
            }else if(clickType == 2){
                changeToParentDialog.dismiss();

                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.home_fragment,parentFragmet).commit();
                changeTextView.setText("学生模式");
                titleModeText.setText("家长模式");
                titleHintText.setVisibility(View.GONE);
            } else if (clickType == 3){
                final PushAgent mPushAgent = PushAgent.getInstance(this);
                int currentChildId = shuShanApplication.getCurrentChildId();
                if(currentChildId > 0){
                    mPushAgent.deleteAlias(currentChildId+"", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                        }
                    });
                }

                int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
                if(useId > 0){
                    mPushAgent.deleteAlias(useId+"", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                        @Override
                        public void onMessage(boolean isSuccess, String message) {
                            Log.i(TAG,"isSuccess=" + isSuccess + " message=" + message);
                        }
                    });
                }

                Intent intent = new Intent(this,LoginOrRegisterActivity.class);
                intent.putExtra("isLogout",true);
                startActivityAllow(intent);

                onBackAction();
                SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
            }

            DialogUtil.dismissParentSetDialog();
        }else{
            showToast("家长密码错误");
            if(veriCodeView != null){
                veriCodeView.clear();
            }

        }
    }

    private void openDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    private void closeDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawers();
        }
    }

    @Override
    public void onControl() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        boolean permissionHasSet = SharedPreferencesUtils.getBooleanDate(Constants.MAIN_PERMISSION_HAS_SET_SHAREPREFERS_KEY);
        if(!permissionHasSet){
            startActivity(PermissionAccessOpenActivity.class);
        }else if(isChildControl){
            showCloseControlDialog();
        }else {
            SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,true);
            Intent intent = new Intent(this, DaemonService.class);
            startService(intent);

            Intent intent1 = new Intent(this,PlayerMusicService.class);
            startService(intent1);

            if(parentFragmet != null){
                parentFragmet.getConrolText().setText("关闭管控");
            }

            showToast("开启管控成功");
        }

    }

    private void logout() {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl || TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY))){
            showLogoutDialog();
            return;
        }
        clickType = 3;
        veriCodeView = DialogUtil.showParentLogoutDialog(this, this, this);
        closeDrawer();

        UmengEventUtil.onProfileSignOff();
    }


    private boolean isVipValide() {
        if(!shuShanApplication.isVip()) {
            showNoVipDialog();

            return false;
        }

        return true;
    }

    private void showNoVipDialog() {
        if(noVipDialog == null){
            noVipDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            noVipDialog.setCanceledOnTouchOutside(true);
            noVipDialog.setCanceledOnTouchOutside(true);
            noVipDialog.setContentView(R.layout.no_vip_dialog);

            Button openButton = noVipDialog.findViewById(R.id.no_vip_open_btn);
            openButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noVipDialog.dismiss();

                    startActivity(OpenVipSpendActivity.class);
                }
            });

            Button shareButton = noVipDialog.findViewById(R.id.no_vip_share_btn);
            shareButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    noVipDialog.dismiss();

                    startActivity(InviteForFreeUseActivity.class);
                }
            });

        }

        if(!noVipDialog.isShowing()){
            noVipDialog.show();
        }
    }

    private void getUpdate() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.APP_VERSION);
        urlParse.putValue("system",Constants.OS_TYPE)
                .putValue("version", TextUtils.isEmpty(versonName)?DeviceUtil.getVersionName(this):versonName);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UpdateBean>() {

                    @Override
                    protected void onSuccess(UpdateBean userBean) {
                        if(userBean != null){
                            versonName = userBean.android_version;
                            boolean isChildControl = SharedPreferencesUtils.getBooleanDate(
                                    Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);

                            if(isChildControl){
                                showPswUpdateDialog(userBean);
                            }else {
                                showUpdateDialog(userBean);
                            }

                            countActiveUse(userBean.time);
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        try {
                            JSONObject jsonObject = new JSONObject(netRetBean.getServerData());
                            countActiveUse(jsonObject.optString("time"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }

    private void showUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_no_psw_dialog);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);


        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });

        Button btnUpdate = updateDialog.findViewById(R.id.update_dialog_update_btn);
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();

                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(HomeActivity.this)//设置上下文
                        .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                        .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                        .setNotificationIconRes(R.drawable.logo)//设置通知图标
                        .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                        .setNotificationTitle("书山宝")//设置通知标题
                        .startDownLoad();//开始下载
            }
        });

        updateDialog.show();
    }

    private void showPswUpdateDialog(final UpdateBean userBean) {
        final Dialog updateDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
        updateDialog.setContentView(R.layout.update_dialog);
        updateDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        updateDialog.setCancelable(false);

        TextView versionText = updateDialog.findViewById(R.id.update_dialog_version_tv);
        versionText.setText(userBean.android_version);
        TextView descText = updateDialog.findViewById(R.id.update_dialog_context_tv);
        descText.setMovementMethod(ScrollingMovementMethod.getInstance());
        descText.setText(userBean.android_update_description);

        final  VerificationCodeView veriCodeView = updateDialog.findViewById(R.id.update_dialog_verification_code_view);
        veriCodeView.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onComplete(String content) {

                if(StringTools.pswValide(content)){
                    updateDialog.dismiss();

                    VersionUpdateConfig.getInstance()//获取配置实例
                            .setContext(HomeActivity.this)//设置上下文
                            .setDownLoadURL(userBean.android_update_url)//设置文件下载链接
                            .setNewVersion(userBean.android_version)//设置即将下载的APK的版本号,避免重复下载
                            .setNotificationIconRes(R.drawable.logo)//设置通知图标
                            .setNotificationSmallIconRes(R.drawable.logo)//设置通知小图标
                            .setNotificationTitle("书山宝")//设置通知标题
                            .startDownLoad();//开始下载
                }else{
                    showToast("家长密码错误");
                    veriCodeView.clear();
                }
            }
        });


        Button btnCancel = updateDialog.findViewById(R.id.update_dialog_cancel_btn);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
            }
        });

        updateDialog.show();
    }

    public void getLoopUserinfo() {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_USER_INFO);
        urlParse.putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

//                        int currentId = shuShanApplication.getCurrentChildId();
//                        if(currentId <= 0 || (!shuShanApplication.isVip())){
//                            mHandler.sendEmptyMessageDelayed(0,DELAY_TIMES);
//                        }

                    }

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if(userBean != null){
                            int currentId = shuShanApplication.getCurrentChildId();
                            if(currentId > 0 && shuShanApplication.isVip() && (!isFinishing()) && userBean.share_vip_last_time == 1){
                                showVipTimeEndDialog(userBean.activity_name);
                            }

                            shuShanApplication.setUserBean(userBean);

                            if(!TextUtils.isEmpty(userBean.password)){
                                SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY,userBean.password);
                            }

                            List<ChildBean> childList = userBean.getChildList();
                            if(childList.size() > 0){
                                new ChildBeanDao(shuShanApplication).dropAndAddList(childList);
                            }else {
                                new ChildBeanDao(shuShanApplication).clearTab();
                            }

                            ChildBean currentChildBean = shuShanApplication.getCurrentChildBean();
                            if(currentChildBean != null){
                                currentChildText.setText(currentChildBean.childName);
                                tvStarNum.setText(currentChildBean.stars + "");

                                tvLevelTerm.setText(ToolUtils.getChildGradeStr(currentChildBean));
                            }

                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNoMsgError(netRetBean);
                    }
                });
    }

    private void showVipTimeEndDialog(String activityName) {
        if(vipTimeEndDialog == null){
            vipTimeEndDialog = new Dialog(this,R.style.Dialog_Translucent_Background);
            vipTimeEndDialog.setContentView(R.layout.dialog_vip_time_end);

            RelativeLayout rlBuyVip = vipTimeEndDialog.findViewById(R.id.rl_btn_buy_vip);
            rlBuyVip.setOnClickListener(this);
            RelativeLayout rlInvite = vipTimeEndDialog.findViewById(R.id.rl_btn_invite);
            rlInvite.setOnClickListener(this);
            if(!TextUtils.isEmpty(activityName)){
                TextView tvActivityName = vipTimeEndDialog.findViewById(R.id.tv_activity_name);
                tvActivityName.setText(activityName);
            }

            ImageView ivClose = vipTimeEndDialog.findViewById(R.id.iv_close_dialog);
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    vipTimeEndDialog.dismiss();
                }
            });

            vipTimeEndDialog.setCancelable(false);
        }

        if(!vipTimeEndDialog.isShowing()){
            vipTimeEndDialog.show();
        }

    }

    private void showNoUsageDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法返回首页，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivity(OpenUsageActivity.class);
                    }
                })
                .create().show();
    }

    private void showLogoutDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("您是否确认退出登录？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        Intent intent = new Intent(HomeActivity.this,LoginOrRegisterActivity.class);
                        intent.putExtra("isLogout",true);
                        startActivityAllow(intent);

                        onBackAction();
                        SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,false);
                    }
                })
                .create().show();
    }

    private void showCloseControlDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("您是否确认关闭管控？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        SharedPreferencesUtils.setBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY,false);

                        Intent intent = new Intent();
                        intent.setAction(Constants.STOP_DAEMON_RECEIVER_ACTION);
                        sendBroadcast(intent);

                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.STOP_PLAY_RECEIVER_ACTION);
                        sendBroadcast(intent1);

                        if(parentFragmet != null){
                            parentFragmet.getConrolText().setText("开启管控");
                        }
                    }
                })
                .create().show();
    }

    private void countActiveUse(String date) {
        if(TextUtils.isEmpty(date)){
            return;
        }

        String activieDay = SharedPreferencesUtils.getStringDate(Constants.ACTIVE_USE_DAY_SHAREPREFERS_KEY
                + shuShanApplication.getCurrentChildId());
        String mobile = SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY);
        Log.i(TAG,"date=" + date + " activieDay=" + activieDay + " mobile=" + mobile);
        if(TextUtils.isEmpty(activieDay)){
            UmengEventUtil.onEvent(shuShanApplication,"users_active_daily_id",mobile);
        }else if(!activieDay.equals(date)){
            UmengEventUtil.onEvent(shuShanApplication,"users_active_daily_id",mobile);
        }

        SharedPreferencesUtils.setStringDate(Constants.ACTIVE_USE_DAY_SHAREPREFERS_KEY
                + shuShanApplication.getCurrentChildId(),date);
    }
}
